var VS_SHADER_RESOURCE =
    "attribute vec4 a_Position;\n" +
    "attribute vec4 a_Color;\n" +
    "varying vec4 v_Color;\n" +
    "void main(){\n" +
    "   v_Color = a_Color;\n" +
    "   gl_Position = a_Position;\n" +
    "}\n";
var FS_SHADER_RESOURCE =
    "precision mediump float;\n" +
    "varying vec4 v_Color;\n" +
    "void main(){\n" +
    "   gl_FragColor = v_Color;\n" +
    "}\n";
var rotaMat;
var curTime;
var u_rotateMat;
var gl;
var angle = 0;
var a_Color;
function main() {
    var canvas = document.getElementById("canvas_id");
    gl = getWebGLContext(canvas);
    if (!gl) {
        console.error("not find gl!!!");
        return
    }
    if (!initShaders(gl, VS_SHADER_RESOURCE, FS_SHADER_RESOURCE)) {
        console.error("init shader fail!!!");
        return
    }
    var n = initShaderBuffer(gl);
    if (n > 0) {
        curTime = Date.now();
        tick();
    }
}



function initShaderBuffer(gl) {
    rotaMat = new Matrix4();
    var buffer = gl.createBuffer();
    if (!buffer) {
        console.error("init cache buffer fail !!");
        return -1;
    }
    var a_Position = gl.getAttribLocation(gl.program, "a_Position");
    // u_rotateMat = gl.getUniformLocation(gl.program, "u_RotateMat");
    // gl.uniform4f(u_color, 1.0,0.0,0.0,1.0);
    var pointArr = new Float32Array(
        [
            0.2, 0.5,
            0.0, 0.2,
            0.5, 0.5
        ]
    );
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, pointArr, gl.STATIC_DRAW);
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(a_Position);

    initColorBuffer(gl);
    return 3;
}


function initColorBuffer(gl) {
    a_Color = gl.getAttribLocation(gl.program, "a_Color");
    var colorBuffer = gl.createBuffer();
    var colorArr = new Float32Array(
        [
            1.0, 0.0, 0.0, 1.0,
            0.0, 1.0, 0.0, 1.0,
            0.0, 0.0, 1.0, 1.0,
        ]
    );
    gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, colorArr, gl.STATIC_DRAW);
    var ret = gl.vertexAttribPointer(a_Color, 4, gl.FLOAT, false, 0, 0);
    // console.log("ret:",ret)
    gl.enableVertexAttribArray(a_Color);
}
function tick() {
    angle += getAniAngle();
    angle %= 360;
    console.log("angel:" + angle);
    draw(gl);
    // requestAnimationFrame(tick);
}

function draw(gl) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    // rotaMat.rotate(angle, 0.0,0.0,1.0);
    // rotaMat.setRotate(angle, 0.0,0.0,1.0);
    // gl.uniformMatrix4fv(u_rotateMat, false,rotaMat.elements);
    gl.drawArrays(gl.TRIANGLES, 0, 3);
}

function getAniAngle() {
    var addangle = (Date.now() - curTime) / 1000 * 30;
    curTime = Date.now();
    return addangle;
}